
package com.wzxy.medical_backed.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzxy.medical_backed.entity.Result;
import com.wzxy.medical_backed.entity.User;
import com.wzxy.medical_backed.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService service;

    // 获取用户列表(分页+搜索)
    @GetMapping("/getAll")
    public Result getAll(@RequestParam(required = false) String search,
                         @RequestParam(defaultValue = "1") Integer page,
                         @RequestParam(defaultValue = "10") Integer size) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (search != null && !search.isEmpty()) {
            queryWrapper.like("userid", search).or().like("fullname", search);
        }
        IPage<User> userPage = service.page(new Page<>(page, size), queryWrapper);
        return new Result("查询成功", userPage, 200);
    }

    // 添加用户
    @PostMapping("/add")
    public Result addUser(@RequestBody User user) {
        boolean saved = service.save(user);
        return saved ? new Result("添加成功", null, 200)
                : new Result("添加失败", null, 400);
    }

    // 更新用户
    @PostMapping("/update")
    public Result updateUser(@RequestBody User user) {
        boolean updated = service.updateById(user);
        return updated ? new Result("更新成功", null, 200)
                : new Result("更新失败", null, 400);
    }

    // 删除用户
    @DeleteMapping("/delete/{id}")
    public Result deleteUser(@PathVariable Long id) {
        boolean removed = service.removeById(id);
        return removed ? new Result("删除成功", null, 200)
                : new Result("删除失败", null, 400);
    }

    // 登录接口(已有)
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid", user.getUserid());
        queryWrapper.eq("password", user.getPassword());
        User user1 = service.getOne(queryWrapper);
        if (user1 != null) {
            return new Result("登录成功", user1, 200);
        } else {
            return new Result("登录失败", null, 400);
        }
    }
}